Ext.define('appfe.stockor.statist.buyinpointgrowinglog.BuyinPointGrowingLogController', {
	extend: 'Ext.app.ViewController',
	alias: 'controller.stockor.statist.buyinpointgrowinglog.BuyinPointGrowingLog',
	/**
 * 清除Grid的内容
 */
	clearGrid: function (button, clickEnven) {
		this.getView().reconfigure(Ext.create('Ext.data.JsonStore', { fields: [], data: [] }), []);
	},
	/**
	 * 点击查询按钮的查询方法
	 */
	searchFn: function (button, clickEnven) {
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		var httpRespJsonObject = myviewmodel.get('httpRespJsonObject');



		var params = this.assembleSearchParams();
		if (params == null || !params || Ext.Object.isEmpty(params)) {
			Ext.Msg.alert('提示', '必须输入查询条件!');
			return;
		}

		Ext.Ajax.request({
			url: BizHttpAction.queryBuyinPointGrowingLog.url,
			method: BizHttpAction.queryBuyinPointGrowingLog.method,
			params: params,
			success: function (response, config) {
				var json = Ext.util.JSON.decode(response.responseText);
				//console.debug("json:", json);
				if (json.success == true) {
					var datas = [];
					console.debug("json.data.datas.length:", json.data.datas.length)
					for (i = 0; i < json.data.datas.length; i++) {
						tmpData = json.data.datas[i];
						//console.debug("json.data.datas[%d]", i, tmpData);
						keyArray = Ext.Object.getKeys(tmpData);
						//console.debug("json.data.datas[%d]", i, keyArray);
						tmpGridRow = {};
						for (m = 0; m < keyArray.length; m++) {
							tmpKey = keyArray[m];
							tmpVal = tmpData[tmpKey];
							if (Ext.typeOf(tmpVal) == 'string') {
								//console.debug("[%d][%d][%s][%s]", i, m, tmpKey ,tmpVal);
								tmpGridRow[tmpKey] = tmpVal;
							} else if (Ext.typeOf(tmpVal) == 'object') {
								//console.debug("[%d][%d][%s][%s]", i, m, tmpKey ,JSON.stringify(tmpVal));
								tmpGridRow[tmpKey] = tmpVal['status'];
								httpRespJsonObject[tmpVal['slimsymbol'] + '-' + tmpKey] = tmpVal;
							}
						}
						datas.push(tmpGridRow);
					}
					//console.debug("datas:", datas);

					var cols = [], columns = [];
					//构建Store的列数据结构
					for (i = 0; i < json.data.columns.length; i++) {
						columns.push(json.data.columns[i]);
					}
					//构建Grid的columns.items的数据结构
					cols.push({ xtype: 'rownumberer', resizable: true });
					for (i = 0; i < columns.length; i++) {
						if (columns[i].name == 'slimsymbol') {//股票代码列
							cols.push({
								header: columns[i].header,
								dataIndex: columns[i].name,
								menuDisabled: false,
								locked: false,
								sortable: false,
								width: 120,
								renderer: 'viewCellSymbolRender'
							})
						} else if (columns[i].name == 'stkname') {//股票名称列
							cols.push({
								header: columns[i].header,
								dataIndex: columns[i].name,
								menuDisabled: false,
								locked: false,
								sortable: false,
								width: 120
							})
						} else {
							cols.push({//股票日期列（显示当天的状态）
								header: columns[i].header,
								dataIndex: columns[i].name,
								menuDisabled: false,
								locked: false,
								sortable: false,
								width: 100,
								// minWidth: 200,
								// flex: 1,
								renderer: 'viewCellStatusRender'
							})
						}
					}
					//获取数据源加入动态的列
					myview.reconfigure(Ext.create('Ext.data.JsonStore', { 'fields': columns, 'data': datas }), cols);
					//!这里是根据标题, 设置自动的宽度
					// Ext.each(myview.columnManager.getColumns(), function (column) {
					// 	if (column.autoSizeColumn === true)
					// 		column.autoSize();
					// });
				} else {
					Ext.Msg.alert('提示', 'http200+fasle, 查询失败!');
				}
			},
			failure: function () {
				Ext.Msg.alert('提示', 'http!200, 查询失败!' + logDate);
			}
		});
	},
	onRender: function () {
		console.debug('onRender');
		this.ajaxBuildSearchPanel();

		console.debug('ajaxBuildSearchPanel done');
	},
	onBoxReady: function () {
		////"value": "2021-11-01 00:00:00",
		console.debug('BuyinPointGrowingLogController.onBoxReady');
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		// var dateNow = new Date();
		// var dateTmp =new Date();
		// var dateAgo7=new Date(dateTmp.setDate(dateTmp.getDate()-7));
		var startDate = myview.lookup('startDate');
		if (startDate) {
			var dateTmp = new Date();
			var dateAgo7 = new Date(dateTmp.setDate(dateTmp.getDate() - 6));
			startDate.setValue(Ext.Date.format(dateAgo7, 'Y-m-d 00:00:00'));
		}
		var endDate = myview.lookup('endDate');
		if (endDate) {
			endDate.setValue(Ext.Date.format(new Date(), 'Y-m-d 23:59:59'));
		}
		//console.debug('startDate', startDate);
	},
	ajaxBuildSearchPanel: function () {
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		var dynaParamPanel = myview.lookup('dynaParamPanel');
		Ext.suspendLayouts();
		Ext.Ajax.request({
			url: BizHttpAction.ajaxBuildSearchPanel.url,
			method: BizHttpAction.ajaxBuildSearchPanel.method,
			async: false,
			success: function (response, config) {
				var json = Ext.util.JSON.decode(response.responseText);
				//console.debug("json:", json);
				if (json.success == true) {
					/*动态加载查询面板的组件*/
					var conditions = json.data.conditions;
					if (!!conditions && !!conditions.length) {
						for (i = 0; i < conditions.length; i++) {
							var newComp = Ext.create(conditions[i]);
							dynaParamPanel.add(newComp);
						}
					}
				} else {
					Ext.Msg.alert('提示', '查询失败!');
				}
			},
			failure: function () {
				Ext.Msg.alert('提示', logDate + '查询失败!');
			}
		});
		Ext.resumeLayouts(true);
	},
	/**
	 * 拼接查询参数
	 */
	assembleSearchParams: function () {
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		var params = {};
		var dynaParamPanel = myview.lookup('dynaParamPanel');
		console.debug('动态面板dynaParamPanel.items=', dynaParamPanel.items.getRange());
		var itemsAll = dynaParamPanel.items.getRange();//获取面板的items中的子对象
		console.debug('assembleSearchParams,面板的items中的子对象.length=', itemsAll.length);
		for (var idx = 0; idx < itemsAll.length; idx++) {
			var tmpComp = itemsAll[idx];
			var compXType = tmpComp.getXType();
			var compRef = tmpComp.getReference();
			var compValue;
			if (compXType == 'button' || compXType == 'buttonyellow') {
				continue;
			} else if (compXType == 'tagfield') {
				compValue = tmpComp.getValue();
				if (compValue == null || compValue.length == 0) {
					Ext.MessageBox.alert('信息提示', '[<font color="#ff3333"><b>' + compLabel + '</b></font>]的列表值不能为空');
					return null;
				}
			} else if (compXType == 'checkboxgroup') {
				var checkObjArray = tmpComp.getChecked();
				var items = [];
				Ext.Array.each(checkObjArray, function (item) {
					items.push(item.name);
				});
				compValue = items;
			} else {
				
				console.debug('compXType=', compXType);
				//BUGFIX
				compValue = tmpComp.getRawValue();
				console.debug('rawValue=%s', tmpComp.getRawValue());
			}
			if (compValue) {
				params[compRef] = compValue;
			}
			//console.debug('label=%s,xtype=%s,ref=%s', tmpComp.getFieldLabel(), compXType, compRef, 'value', compValue);
		}
		return params;
	},
	/**
	 * 
	 */
	viewCellSymbolRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var slimsymbol = record.get('slimsymbol');
		var stkname = record.get('stkname');
		var changeTypeFmtStr = '<a title="查看雪球行情页面&#13;代码:{1}&#10;名称:{2}" href="https://xueqiu.com/S/{0}" target="_blank">{1}</a>';
		return Ext.String.format(changeTypeFmtStr, slimsymbol.toUpperCase(), slimsymbol, stkname);
	},
	viewCellStatusRender: function (value, metaData, record, rowIndex, colIndex, store, view) { /**	渲染cell */
		if (colIndex == 0 || colIndex == 1) {
			return value;
		}
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		var slimsymbol = record.get('slimsymbol');
		var stkname = record.get('stkname');
		var jsonObj = myviewmodel.get('httpRespJsonObject');
		var lineData = jsonObj[slimsymbol + '-' + myview.getColumns()[colIndex].dataIndex];
		// console.debug('key', slimsymbol + '-' + myview.getColumns()[colIndex].dataIndex);
		// console.debug('lineData', lineData);
		var grade, open, close, high, low, profitAmount, profitRatio, closeOverMa5, ma5OverMa10, ma5OverMa13;
		if (lineData) {
			try {
				grade = lineData['grade'];
				open = Ext.util.Format.number(lineData['topenPrice'], '￥0.00');
				close = Ext.util.Format.number(lineData['tclosePrice'], '￥0.00');
				high = Ext.util.Format.number(lineData['thighPrice'], '￥0.00');
				low = Ext.util.Format.number(lineData['tlowPrice'], '￥0.00');
				profitAmount = Ext.util.Format.number(lineData['tcloseIncreaseAmount'], '￥0.00');
				profitRatioNumVal = lineData['tcloseProfitRatio'];
				profitRatio = Ext.util.Format.number(profitRatioNumVal * 100, '0.00%');
				closeOverMa5 = lineData['closeOverMa5'] ? "■" : "□";
				ma5OverMa10 = lineData['ma5OverMa10'] ? "■" : "□";
				ma5OverMa13 = lineData['ma5OverMa13'] ? "■" : "□";
			} catch (e) { console.debug('e', e); }
		} else {
			return value;
		}
		var formatTpl = '状态: {0}'
			+ '<br>代码: {1} ,名称: {2}'
			+ '<br>级别: {3}'
			+ '<br>开: {4} ,收: {5} ,高: {6} ,低: {7}'
			+ '<br>利润额: {8} ,率: {9}'
			+ '<br>收≥MA5: {10} ,MA5≥10: {11} ,MA5≥13: {12}';


		var newValue, newValueColor;
		if (value === 'NEW') {
			var tooltipStr = Ext.String.format(formatTpl, '新建', slimsymbol, stkname, grade, open, close, high, low, profitAmount, profitRatio, closeOverMa5, ma5OverMa10, ma5OverMa13);
			metaData.tdAttr = 'data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '"';
			//metaData.tdStyle = 'color:#00A800';
			newValue = '新';
			newValueColor = 'color:#00A800;';
			newValueBgColor = 'background-color:rgba(0,168,0,0.1);';
		} else if (value === 'OPEN') {
			var tooltipStr = Ext.String.format(formatTpl, '有效', slimsymbol, stkname, grade, open, close, high, low, profitAmount, profitRatio, closeOverMa5, ma5OverMa10, ma5OverMa13);
			metaData.tdAttr = 'data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '"';
			//metaData.tdStyle = 'color:#FF920D';
			newValue = '开';
			newValueColor = 'color:#FF920D;';
			newValueBgColor = '';
		} else if (value === 'CLOSE') {
			var tooltipStr = Ext.String.format(formatTpl, '关闭', slimsymbol, stkname, grade, open, close, high, low, profitAmount, profitRatio, closeOverMa5, ma5OverMa10, ma5OverMa13);
			metaData.tdAttr = 'data-qtip="' + Ext.String.htmlEncode(tooltipStr) + '"';
			//metaData.tdStyle = 'color:#000000';
			newValue = '关';
			newValueColor = 'color:white;';
			newValueBgColor = 'background-color:rgba(0,0,0,0.3);';
		} else {
			return value;
		}


		if (Ext.typeOf(profitRatioNumVal) != 'number' && Ext.Object.isEmpty(profitRatioNumVal)) {
			profitAmountColor = 'black';
			profitRatioBgColor = 'black';
		} else {
			if (profitRatioNumVal > 0 && profitRatioNumVal <= 0.1) {
				profitAmountColor = 'color:red;';
				profitRatioColor = 'color:white;';
				profitRatioBgColor = 'background-color:red;';
			} else if (profitRatioNumVal > 0.1) {
				profitAmountColor = 'color:FireBrick;';
				profitRatioColor = 'color:white;';
				profitRatioBgColor = 'background-color:FireBrick;';
			} else if (profitRatioNumVal < 0) {
				profitAmountColor = 'color:green;';
				profitRatioColor = 'color:white;';
				profitRatioBgColor = 'background-color:green;';
			} else {
				profitAmountColor = 'color:black;';
				profitRatioColor = 'color:black;';
				profitRatioBgColor = '';
				profitAmount = close;
				profitRatio = '收盘价';
			}
		}
		return '<div style="float:left; ' + newValueBgColor + '' + newValueColor + ' font-size:22px; font-weight:bold; height:40px;line-height:36px;">' +
			'<span style="display:inline-block; vertical-align: bottom;">' + newValue + '</span></div>'
			+ '<div style="float:right;">'
			+ '<div style="' + profitAmountColor + 'font-size:12px; padding:0px 0px 0px 10px;">' + profitAmount + '</div>'
			+ '<div style="' + profitRatioColor + profitRatioBgColor + 'font-size:12px; padding:0px 0px 0px 10px;">' + profitRatio + '</div>'
			+ '</div>';
	},
	/**
	 * 渲染cell
	 */
	renderLine: function (value, metaData, record, rowIndex, colIndex, store, view) {
		if (view.isLockedView == true) {//锁定列
			metaData.tdAttr = 'bgcolor="#00A800"';
			metaData.tdStyle = 'color:white';
			return value;
		}
		//value有特殊标识的四字命令, WEND代表周末
		if (value == 'WEND') {
			metaData.tdAttr = 'bgcolor="#a6a6a8"';
			//metaData.style = "display: none";
			return '';
		}
		/*
		一人一天的任务有多个, 用||分隔, 一个任务的ID,type,名称用^^分隔
		多个任务放在一个cell展示, 用br回车多行
		*/
		var taskArray = value.split('||');
		var formattedStr;
		//console.debug("taskArray.length:", taskArray.length);
		for (i = 0; i < taskArray.length; i++) {
			var taskStr = taskArray[i];
			var valueArray = taskStr.split('^^');
			if (valueArray.length == 1) {
				//只有一个任务名称
				if (i == 0) {
					formattedStr = value;
				} else {
					formattedStr = formattedStr + '<br/>' + value;
				}
			} else if (valueArray.length >= 3) {
				//有任务ID, 任务类型和任务全称
				//metaData.tdAttr = 'data-qtip="' + valueArray[2] + '"';
				var changeTypeFmtStr = '<a style="color: #000000;text-decoration: none;" href="http://project.corp.daling.com/zentao/task-view-{0}.html" title="{2}" target="_blank">&raquo;[{0}]{2}</a>';
				var value = Ext.String.format(changeTypeFmtStr, valueArray[0], valueArray[1], valueArray[2]);
				if (i == 0) {
					formattedStr = value;
				} else {
					formattedStr = formattedStr + '<br/>' + value;
				}
			}
		}
		//实现换行
		metaData.style = 'overflow:auto;padding: 3px 6px;text-overflow: ellipsis;white-space: nowrap;white-space:normal;line-height:20px;';
		return formattedStr;//+"<br/>"+formattedStr2;
	},

	/**
	 * grid cell 将html特殊字符替换
	 */
	renderCellPlainText: function (value) {
		return value ? value.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#39;') : value;
	}
});